package com.shop.util;

import com.shop.api.ProductApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class UploadUtil {
    private static final Logger logger = LoggerFactory.getLogger(ProductApi.class);

    public static String insertOrderImg(MultipartFile file) {


        // 文件上传路径
        String location = "E:\\shopping\\taojin\\src\\main\\resources\\upload\\";

        if (!file.isEmpty()) {
            //获取文件大小
            long size = file.getSize() / 1024; //kb
            if (size > 1024) { //判断图片大小 单位kb
                return "50051";
            }
            // 获取文件原始名称 a.png -> a
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀 .png
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));

            //设置允许上传文件类型
            String suffixList = ".jpg,.png,.ico,.bmp,.jpeg";
            // 判断是否包含
            if (suffixList.contains(extName.trim().toLowerCase())) {
                // 保存文件的路径
                String fileName = UUID.randomUUID() + extName;
                String path = location + fileName;

                // 查看路径是否存在，不存在就创建
                //image/jpeg
                if (!new File(path).exists()) {
                    boolean mkdirs = new File(path).mkdirs();
                }
                //  spring的transferTo保存文件方法
                try {
                    file.transferTo(new File(path));
                    String imgUrl = "/photos/" + fileName;

                    return imgUrl;

                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("上传文件出错！");
                    return "50050";
                }
            }else{
                return "50052";
            }
        }
        return "50053";
    }
}
